import React, { useState, forwardRef, useImperativeHandle } from 'react'
import { Toast, ActionSheet } from 'react-vant'
import { Passed } from '@react-vant/icons'

const ShareComponent = forwardRef(({ actions, shareContent }, ref) => {
  const [more, setMore] = useState(false)

  const showMenu = () => {
    setMore(!more)
  }

  // 复制链接
  const copyLink = link => {
    const pEle = document.createElement('p')
    pEle.innerHTML = link || ''
    document.body.appendChild(pEle)

    const range = document.createRange() // 创造range
    window.getSelection().removeAllRanges() //清除页面中已有的selection
    range.selectNode(pEle) // 选中需要复制的节点
    window.getSelection().addRange(range)

    const copyStatus = document.execCommand('Copy') // 执行copy操作
    Toast({
      message: '复制成功',
      icon: <Passed />
    })
    document.body.removeChild(pEle)
    window.getSelection().removeAllRanges()
  }

  // 操作 分享
  const Select = (action, index) => {
    let linkStr = `https://weibo.com/${shareContent.mblog.user.id}/${shareContent.mblog.bid}`
    if (index === 0) {
      copyLink(linkStr)
    } else {
      navigator.share({
        //要共享的标题
        title: shareContent.title,
        //要共享的 URL
        url: linkStr,
        //要共享的文本
        text: ''
      })
      Toast({
        message: '分享成功',
        icon: <Passed />
      })
    }
    setMore(!more)
  }

  useImperativeHandle(ref, () => ({
    showMenu: showMenu
  }))

  return (
    <>
      <ActionSheet
        round={false}
        onSelect={(action, index) => Select(action, index)}
        visible={more}
        onCancel={() => showMenu()}
        actions={actions}
        cancelText="取消"
      />
      1
    </>
  )
})

export default ShareComponent
